package de.szut.traineeslife;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import org.xml.sax.DTDHandler;

import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.EditText;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;

import de.szut.traineeslife.adapter.FilesFromSDAdapter;
import de.szut.traineeslife.data.User;
import de.szut.traineeslife.fragments.SearchModelDialogFragment;
import de.szut.traineeslife.fragments.SelectModelDialogFragment;
import de.szut.traineeslife.fragments.WelcomeDialogFragment;
import de.szut.traineeslife.taks.PrepareDriveTask;
import de.szut.traineeslife.taks.LoadDocumentsTask;
import de.szut.traineeslife.taks.UploadToDriveTask;
import de.szut.traineeslife.utils.Constants;
import de.szut.traineeslife.utils.DateHelper;
import de.szut.traineeslife.utils.DialogListener;
import de.szut.traineeslife.utils.DriveHelper;
import de.szut.traineeslife.utils.FileHelper;
import de.szut.traineeslife.utils.PreferenceHandler;
import de.szut.traineeslife.utils.ProfilHelper;

public class AuthenticationActivity extends SherlockFragmentActivity implements DialogListener {

	private String accountName;
	static final int REQUEST_ACCOUNT_PICKER = 1;
	static final int REQUEST_AUTHORIZATION = 2;
	private static Drive service;
	private static GoogleAccountCredential credential;
	private DateHelper dateHelper;
	private ProfilHelper profilHelper;
	private FileHelper fileHelper;
	private DriveHelper driveHelper;
	private PreferenceHandler prefsHandler;
	private Dialog profilDialog;
	private String selectedModelFolderPath;
	private WelcomeDialogFragment welcomeDialog;
	private SearchModelDialogFragment searchModelDialog;
	private SelectModelDialogFragment selectModelDialog;
	private ArrayList<File> listOfModelsInFolder;
	private DialogFragment currentDialog;
	private String currentDialogTag;
	private boolean isDialogReady = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.authentication);
		prefsHandler = new PreferenceHandler(getBaseContext());
		fileHelper = new FileHelper();
		profilHelper = new ProfilHelper();
		dateHelper = new DateHelper();
		driveHelper = new DriveHelper();
		if (savedInstanceState == null) {
			authenticateGoogleAccount();
			startWelcomeDialog();
		} else {
			accountName = savedInstanceState.getString(Constants.ACC_SAVE_TAG);
			currentDialog = (DialogFragment) getSupportFragmentManager().findFragmentByTag(savedInstanceState.getString(Constants.DLG_SAVE_TAG));
			getSupportFragmentManager().beginTransaction().add(currentDialog, savedInstanceState.getString(Constants.DLG_SAVE_TAG)).addToBackStack(null).commit();
			currentDialogTag = currentDialog.getTag();
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT_PICKER:
			if (resultCode == RESULT_OK && data != null && data.getExtras() != null) {
				accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				if (accountName != null) {
					credential.setSelectedAccountName(accountName);
					PreferenceHandler handler = new PreferenceHandler(this);
					handler.saveGoogleAcc(null);// accountname
					service = getDriveService(credential);
				}
			}
			break;
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(Constants.DLG_SAVE_TAG, currentDialogTag);
		outState.putString(Constants.ACC_SAVE_TAG, accountName);
	}

	/**
	 * Starts an Intent to choose a google account from Device
	 */
	private void authenticateGoogleAccount() {
		credential = GoogleAccountCredential.usingOAuth2(this, DriveScopes.DRIVE);
		startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
	}
	
	/**
	 * Creats the Service to get Connection to Google Drive
	 * @param accountNamen
	 * @param context
	 */
	public static void createDriveServie(String accountNamen, Context context) {
		GoogleAccountCredential accountCredential = GoogleAccountCredential.usingOAuth2(context, DriveScopes.DRIVE);
		accountCredential.setSelectedAccountName(accountNamen);
		service = getDriveService(accountCredential);

	}

	/**Returns a new Drive Service if the current Service was null
	 * @param credential
	 * @return
	 */
	private static Drive getDriveService(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(), new GsonFactory(), credential).build();
	}

	public static Drive getService() {
		return service;
	}

	public static void setService(Drive service) {
		AuthenticationActivity.service = service;
	}

	/* Starts the First DialogFragment 
	 * (non-Javadoc)
	 * @see de.szut.traineeslife.utils.DialogListener#startWelcomeDialog()
	 */
	@Override
	public void startWelcomeDialog() {
		welcomeDialog = WelcomeDialogFragment.newInstance(profilDialog, profilHelper, dateHelper);
		getSupportFragmentManager().beginTransaction().add(welcomeDialog, welcomeDialog.getTAG()).addToBackStack(null).commit();
		currentDialogTag = welcomeDialog.getTAG();
	}

	/*
	 *  (non-Javadoc)
	 * @see de.szut.traineeslife.utils.DialogListener#backToWelcomeDialog()
	 */
	@Override
	public void backToWelcomeDialog() {
		getSupportFragmentManager().popBackStackImmediate();
		currentDialogTag = welcomeDialog.getTAG();
	}

	/* Starts the DialogFragment to Search for the Reportsmodel
	 * (non-Javadoc)
	 * @see de.szut.traineeslife.utils.DialogListener#startSearchModelDialog()
	 */
	@Override
	public void startSearchModelDialog() {
		searchModelDialog = SearchModelDialogFragment.newInstance(profilDialog, fileHelper);
		getSupportFragmentManager().beginTransaction().add(searchModelDialog, searchModelDialog.getTAG()).addToBackStack(null).commit();
		currentDialogTag = searchModelDialog.getTAG();
	}

	/* Starts the DialogFragment to Select a Model
	 * (non-Javadoc)
	 * @see de.szut.traineeslife.utils.DialogListener#startSelectModelDialog(java.util.ArrayList)
	 */
	@Override
	public void startSelectModelDialog(ArrayList<File> listOfDoc) {
		selectModelDialog = SelectModelDialogFragment.newInstance(profilDialog, profilHelper, driveHelper, fileHelper, listOfDoc);
		getSupportFragmentManager().beginTransaction().add(selectModelDialog, selectModelDialog.getTAG()).addToBackStack(null).commit();
		currentDialogTag = selectModelDialog.getTAG();
	}

	@Override
	public void backToSerachModelDialog() {
		getSupportFragmentManager().popBackStackImmediate();

	}

	@Override
	public String getSelectedModelFolderPath() {
		return selectedModelFolderPath;
	}

	@Override
	public void setSelectedModelFolderPath(String path) {
		selectedModelFolderPath = path;
	}

	@Override
	public void setSelectedModelPath(String path) {
		// TODO Auto-generated method stub

	}

	@Override
	public String getSelectedModelPath() {
		// TODO Auto-generated method stub
		return null;
	}

	public ArrayList<File> getListOfModelsInFolder() {
		return listOfModelsInFolder;
	}

	@Override
	public ArrayList<File> getListOfDocs() {
		return listOfModelsInFolder;
	}

	@Override
	public void setListOfDocs(ArrayList<File> fileList) {
		listOfModelsInFolder = fileList;
		Log.d("LISTOFMODELS", Integer.toString(fileList.size()));
	}

	/* Stop this Activity if Authenitcation is ready an starts the Main part the write the reports
	 * (non-Javadoc)
	 * @see de.szut.traineeslife.utils.DialogListener#finishAuthentication()
	 */
	@Override
	public void finishAuthentication() {
		Intent i = new Intent(AuthenticationActivity.this, TraineesLifeActivity.class);
		i.putExtra(Constants.PREFS_TAG, prefsHandler.getPreferences().getString(prefsHandler.getPREFS_KEY(), ""));
		i.putExtra(Constants.DATEHELPER_TAG, dateHelper);
		i.putExtra(Constants.PROFILHELPER_TAG, profilHelper);
		startActivity(i);
		AuthenticationActivity.this.finish();

	}

}
